package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Sets;
import com.joint.base.bean.EnumManage;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.*;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.Employees;
import com.joint.core.entity.Change;
import com.joint.core.entity.PersonnelResume;
import com.joint.core.service.ChangeService;
import com.joint.core.service.EmployeesService;
import com.joint.core.service.PersonnelResumeService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxTransferAction extends BaseFlowAction {

    @Resource
    private ChangeService changeService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private EmployeesService employeesService;
    @Resource
    private PowerService powerService;
    @Resource
    private RemindService remindService;
    @Resource
    private ReadersService readersService;
    @Resource
    private PersonnelResumeService personnelResumeService;

    private Employees employees;
    private Users loginUser;
    private Change change;
    private String createDate;
    private Users creater;
    private String departId;
    private String postId;
    private int ifCentralStaff;
    private BigDecimal money;
    private String reason;
    private BigDecimal oldMoney;
    private String name;
    private String nature;
    private String natureValue;
    private String remark;

    /**
     * 下一步审批人的Name的集合，用逗号分隔
     */
    private String nextStepApproversName;

    /**
     * 下一步审批人的id的集合，用逗号分隔
     */
    private String nextStepApproversId;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 详情
     * @return
     */
    public String read(){

        loginUser=usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            change =changeService.get(keyId);
            LogUtil.info("change"+change.getName());
            //sex=change.getSex().value();
            String nature = change.getNature();
            if (StringUtils.isNotEmpty(nature)){
                if(nature.equals("0")){
                    natureValue="正式";
                }else if(nature.equals("1")){
                    natureValue="试用";
                }else {
                    natureValue="聘用";
                }
            }
            numStatus = workflowService.getNumStatus(keyId, loginUser);
            createDate=DataUtil.DateToString(change.getCreateDate(),"yyyy-MM-dd");

        }

        return "read";
    }

    /**
     * 加载数据
     * @return
     */
    public String loadDate(){

        loginUser=usersService.getLoginInfo();
        employees = employeesService.get(parentId);
        String oldPost = employees.getEmpPost().getName();
        Map<String,String> data=new HashMap<String, String>();

        String nature = employees.getNature();
        if (nature.equals("0")){
            data.put("natureValue","正式");
        }else if(nature.equals("1")){
            data.put("natureValue","试用");
        }else if(nature.equals("2")){
            data.put("natureValue","聘用");
        } else {
            data.put("natureValue", " ");
        }
        BigDecimal money = employees.getMoney();
        data.put("oldPost",oldPost);
        data.put("nature",nature);
        data.put("oldMoney", String.valueOf(money));
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    /**
     * 新建／编辑
     * @return
     */
    public String input(){
        loginUser=usersService.getLoginInfo();

        if (StringUtils.isNotEmpty(keyId)){

            change= changeService.get(keyId);
            employees=change.getEmployees();
            String nature = change.getNature();
            if (StringUtils.isNotEmpty(nature)){
                if(nature.equals("0")){
                    natureValue="正式";
                }else if(nature.equals("1")){
                    natureValue="试用";
                }else {
                    natureValue="聘用";
                }
            }
            creater=change.getCreater();
            createDate=DataUtil.DateToString(change.getCreateDate(),"yyyy-MM-dd");
        } else {

            if(StringUtils.isNotEmpty(parentId)){
                employees=employeesService.get(parentId);
            }
            creater=loginUser;
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");
        }

        return "input";
    }

    private void setData(){

        Set<Users> usersSet= Sets.newHashSet();
        if(StringUtils.isNotEmpty(keyId)){
            change = changeService.get(keyId);
            employees=change.getEmployees();
        }else{
            change = new Change();
            change.setCreater(usersService.getLoginInfo());
        }

        if(StringUtils.isNotEmpty(postId)){
            change.setPost(postService.get(postId));
        }
        if(StringUtils.isNotEmpty(departId)){
            change.setDepartment(departmentService.get(departId));
        }
        //更新employees
        if(StringUtils.isNotEmpty(parentId)){
            employees = employeesService.get(parentId);
            /*// Users users = employees.getUsers();
            //LogUtil.info("QQQ"+users.getName());
            if(StringUtils.isNotEmpty(departId)){
                employees.setDep(departmentService.get(departId));
            }
            if(StringUtils.isNotEmpty(postId)){
                employees.setEmpPost(postService.get(postId));
            }
            employees.setMoney(money);
            employeesService.update(employees);*/
            change.setEmployees(employees);
            // change.setUsers(users);
        }
        Set<Duty> dutySet = usersService.getLoginInfo().getDutySet();
        for (Duty duty:dutySet){
            if(duty.getDepartment().getParent()!=null){
                LogUtil.info("ceshi"+duty.getDepartment().getParent().getName());
                if(StringUtils.equals(duty.getDepartment().getParent().getName(),"产业中心")){
                    change.setIfCentralStaff(1);
                }
            }

        }
        change.setNextStepApproversId(nextStepApproversId);
        change.setNextStepApproversName(nextStepApproversName);
        change.setMoney(money);
        change.setOldMoney(oldMoney);
        change.setFileType("0");
        change.setName(name);
        change.setReason(reason);
        change.setNature(nature);
        change.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                changeService.update(change);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                changeService.save(change, "transfer", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        ArrayList<String> list = new ArrayList<String>();
        for (String uid: nextStepApproversId.split(",")) {
            list.add(uid.trim());
        }
        ArrayList<String> list1 = new ArrayList<String>();
        for (String uid: nextStepApproversId.split(",")) {
            list1.add(uid.trim());
        }

        var2.put("approvers", list);    // 会签人Ids
        var2.put("ifCentralStaff", change.getIfCentralStaff());

        try {
            if (StringUtils.isNotEmpty(keyId)) {
                changeService.approve(change, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                keyId=changeService.commit(change, "transfer", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        Set<Users> usersSet= Sets.newHashSet();
        usersSet=change.getEmployees().getEmployment().getManage().getChargeUsers();

        //增加归档后读者
        for(Users users:usersSet) {
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("change");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        for(Users users:usersSet){
            Remind remind = new Remind();
            remind.setUsers(users);
            remind.setBussinessKey("change");
            remind.setKeyId(keyId);
            remind.setContent("员工调动已归档");
            remindService.save(remind);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 审批1
     * @return
     */
    public String approve1(){
        change = changeService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        if(change.getIfCentralStaff()==1){
            var1.put("numStatus",3);
        }else{
            var1.put("numStatus", 2);

        }
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                changeService.approve(change, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 审批2
     * @return
     */
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        change = changeService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 3);
        PersonnelResume personnelResume = new PersonnelResume();
        //  var2.put("curDutyId", curDutyId);
        try {
            changeService.approve(change, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            if(change.getEmployees()!=null) {
                employees = change.getEmployees();
                employees.setMoney(money);
                Department department = departmentService.get(departId);
                Post post = postService.get(postId);
                Users users = employees.getUsers();
                Set<Duty> dutySet = users.getDutySet();
                for (Duty duty:dutySet){
                    LogUtil.info("duty"+duty);
                    duty.setState(BaseEnum.StateEnum.Delete);
                    dutyService.delete(duty);
                }
                Power power = powerService.getPowerByDepartAndPost(department, post);
                Duty duty = new Duty(users, power, department, post);
                duty.setCompany(usersService.getCompanyByUser());
                duty.setDutyState(EnumManage.DutyState.Default);
                dutyService.save(duty);
                //更改employee
                if (StringUtils.isNotEmpty(departId)){
                    employees.setDep(departmentService.get(departId));

                }
                if (StringUtils.isNotEmpty(postId)){
                    employees.setEmpPost(postService.get(postId));
                }
                employeesService.update(employees);

                Users user = employees.getUsers();
                personnelResume.setUsers(user);
                personnelResume.setType("调动申请");
                personnelResume.setCompany(usersService.getLoginInfo().getCompany());
                personnelResumeService.save(personnelResume);
            }

            } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 会签
     * @return
     */
    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";

        change = changeService.get(keyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        // var2.put("curDutyId", curDutyId);
        try {
            changeService.approve(change, FlowEnum.ProcessState.Running, var2, curDutyId, comment);

            Task overtask = workflowService.getCurrentTask(keyId);
            LogUtil.info("overtask:"+overtask);
            if(overtask==null){
                Change entity=changeService.get(keyId);
                PersonnelResume personnelResume = new PersonnelResume();
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                changeService.update(entity);
                if(change.getEmployees()!=null) {
                    employees = change.getEmployees();
                    employees.setMoney(money);
                    Department department = departmentService.get(departId);
                    Post post = postService.get(postId);
                    Users users = employees.getUsers();
                    Set<Duty> dutySet = users.getDutySet();
                    for (Duty duty:dutySet){
                        LogUtil.info("duty"+duty);
                        duty.setState(BaseEnum.StateEnum.Delete);
                        dutyService.delete(duty);
                    }
                    Power power = powerService.getPowerByDepartAndPost(department, post);
                    Duty duty = new Duty(users, power, department, post);
                    duty.setCompany(usersService.getCompanyByUser());
                    duty.setDutyState(EnumManage.DutyState.Default);
                    dutyService.save(duty);
                    if (StringUtils.isNotEmpty(departId)){
                        employees.setDep(departmentService.get(departId));

                    }
                    if (StringUtils.isNotEmpty(postId)){
                        employees.setEmpPost(postService.get(postId));
                    }
                    employeesService.update(employees);

                    Users user = employees.getUsers();
                    personnelResume.setUsers(user);
                    personnelResume.setType("调动申请");
                    personnelResume.setCompany(usersService.getLoginInfo().getCompany());
                    personnelResumeService.save(personnelResume);
                }

            }else {

                if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){

                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 4);
                }
            }

        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }


    /**
     * 退回
     * @return
     */
    public String reject() {
        if (StringUtils.isNotEmpty(keyId)) {
            change = changeService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("transfer");
            String key=activityList.get(0).getId();
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            changeService.reject(change, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }


    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public Change getTransfer() {
        return change;
    }

    public void setTransfer(Change change) {
        this.change = change;
    }

    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public Users getCreater() {
        return creater;
    }

    public void setCreater(Users creater) {
        this.creater = creater;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public int getIfCentralStaff() {
        return ifCentralStaff;
    }

    public void setIfCentralStaff(int ifCentralStaff) {
        this.ifCentralStaff = ifCentralStaff;
    }

    public String getNextStepApproversName() {
        return nextStepApproversName;
    }

    public void setNextStepApproversName(String nextStepApproversName) {
        this.nextStepApproversName = nextStepApproversName;
    }

    public String getNextStepApproversId() {
        return nextStepApproversId;
    }

    public void setNextStepApproversId(String nextStepApproversId) {
        this.nextStepApproversId = nextStepApproversId;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public Employees getEmployees() {
        return employees;
    }

    public void setEmployees(Employees employees) {
        this.employees = employees;
    }

    public BigDecimal getMoney() {
        return money;
    }

    public void setMoney(BigDecimal money) {
        this.money = money;
    }

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public BigDecimal getOldMoney() {
        return oldMoney;
    }

    public void setOldMoney(BigDecimal oldMoney) {
        this.oldMoney = oldMoney;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNature() {
        return nature;
    }

    public void setNature(String nature) {
        this.nature = nature;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public Change getChange() {
        return change;
    }

    public void setChange(Change change) {
        this.change = change;
    }

    public String getNatureValue() {
        return natureValue;
    }

    public void setNatureValue(String natureValue) {
        this.natureValue = natureValue;
    }

}
